<script setup lang="ts">
import 'vue3-tree-org/lib/vue3-tree-org.css'
import { Vue3TreeOrg } from 'vue3-tree-org'
import { cloneDeep, omit } from 'lodash-es'
import { treeOrgConfig } from '../index'
import type {
  CalculationStatusMonitoringSelectCalculationStatusPageResult1 as A,
  CalculationStatusMonitoringPublicParams,
  CalculationStatusMonitoringPublicResult,
  DictionaryEncoInfo,
} from '@/types'
import { calculationStatusMonitoringApi } from '@/api'
// ------------------use------------------
// #region
const props = defineProps<{
  info: A['baseDataValInternalList'][number] | null
  dateType: string
  timeTypeOptions: DictionaryEncoInfo[]
}>()

const [isPopover, setIsPopover] = useState(false)
const [targetRef, setTargetRef]
  = useState<HTMLElement | null>(null)
const [isShow, setIsShow] = useState(false)
const [treeData, setTreeData]
  = useState<CalculationStatusMonitoringPublicResult | null>(
    null,
  )
const [selectNode, setSelectNode]
  = useState<CalculationStatusMonitoringPublicResult | null>(
    null,
  )
const { withLoading, vLoading } = useDefineLoading({
  destroyNode: true,
})
// #endregion
// ------------------静态变量------------------
// #region

// #endregion
// ------------------动态变量------------------
// #region

// #endregion
// ------------------ref-----------
// #region
// #endregion
// ------------------reactive------
// #region
// #endregion
// ------------------computed------
// #region

// #endregion
// ------------------生命周期------------------
// #region

// #endregion
// ------------------内置方法---------------------
// #region
// #endregion
// ------------------方法---------------------
// #region
function getTimeLabel(key?: string) {
  if (!key)
    return ''
  return (
    props.timeTypeOptions.find(item => item.dicKey === key)
      ?.dicValue || ''
  )
}
async function open() {
  setIsShow(true)
  await nextTick()
  setTreeData(null)
  getTreeData()
}
function close() {
  setIsShow(false)
}
async function getTreeData() {
  const { dataTime, indicatorNumber } = unref(props.info)!
  const params: Omit<
    CalculationStatusMonitoringPublicParams,
    'indicatorName'
  > = {
    dataTime,
    indicatorNumber: indicatorNumber as string,
    key: props.dateType,
  }
  const { data: res } = await withLoading(
    calculationStatusMonitoringApi.selectCalculateRelationships,
  )(params)
  setTreeData(res)
}
let timer: NodeJS.Timeout | null = null

async function hide() {
  timer && clearTimeout(timer)
  await nextTick()
  setIsPopover(false)
}
async function handleNodeDrag() {
  await hide()
  // console.log('handleNodeDrag');
}
async function handleNodeMouseleave() {
  await hide()
  // console.log('handleNodeMouseleave');
}
function handleDragEnd() {
  // console.log('handleDragEnd');
  setIsPopover(true)
}
function handleNodeMouseenter(e: MouseEvent, data: any) {
  const newData = omit(cloneDeep(data), 'indicatorNumber')
  const isR = Object.values(newData).every(
    item => item === null,
  )
  if (isR)
    return
  console.log('handleNodeMouseenter', data, isR)

  timer = setTimeout(async () => {
    // if (node.children.length !== 0) {
    //   timer && clearTimeout(timer);
    //   return;
    // }
    setTargetRef(e.target! as HTMLElement)
    await nextTick()
    setIsPopover(true)
    setSelectNode(data)
  }, 300)
}

// const a = once(() => {
//   setIsPopover(false);
// });
// const b = debounce(() => {
//   setIsPopover(true);
// }, 300);
// const handleZoom = () => {
//   a();
//   b();
// };
// #endregion
defineExpose({
  open,
  close,
})
</script>

<template>
  <FullscreenModal
    v-model="isShow"
    class="flex-direction flex"
  >
    <el-page-header
      title="返回"
      content="指标计算关系图"
      class="flex-incompressible margin-bottom-sm"
      @back="close"
    />
    <div v-loading class="flex-fillRemaining">
      <el-empty
        v-show="!treeData"
        description="请切换其他时间段查看"
      />
      <Vue3TreeOrg
        v-show="treeData"
        ref="treeOrgRef"
        v-bind="(treeOrgConfig as any)"
        :data="treeData ?? {}"
        class="height-fill box-border"
        @on-node-mouseenter="handleNodeMouseenter"
        @on-node-mouseleave="handleNodeMouseleave"
        @on-drag="handleNodeDrag"
        @on-drag-stop="handleDragEnd"
      >
        <!-- 自定义节点内容 -->
        <template #default="{ node }">
          <div
            class="node-label c-pointer tree-org-node__text"
          >
            <div>{{ node.label }}</div>
            <div v-show="node.$$data.timeType">
              时间类型：{{
                getTimeLabel(node.$$data.timeType)
              }}
            </div>
          </div>
        </template>
      </Vue3TreeOrg>
    </div>
    <el-popover
      placement="left"
      :width="400"
      :show-after="300"
      :visible="isPopover"
      :virtual-ref="targetRef"
      virtual-triggering
      :popper-options="{
        modifiers: [
          {
            name: 'computeStyles',
            options: {
              adaptive: false,
              enabled: false,
            },
          },
        ],
      }"
      append-to=".container"
    >
      <el-descriptions
        title="详情"
        :column="1"
        size="small"
        border
        :min-width="50"
        class="width-fill ppp-description"
      >
        <el-descriptions-item label="计算公式">
          {{ selectNode?.formulaContent }}
        </el-descriptions-item>
        <el-descriptions-item
          v-show="selectNode?.indicatorCode"
          label="点位号"
        >
          {{ selectNode?.indicatorCode }}
        </el-descriptions-item>
        <el-descriptions-item
          v-show="selectNode?.dataTime"
          label="数据时间"
        >
          {{ selectNode?.dataTime }}
        </el-descriptions-item>
        <el-descriptions-item
          v-show="selectNode?.timeType"
          label="时间周期"
        >
          {{ getTimeLabel(selectNode?.timeType) }}
        </el-descriptions-item>
        <el-descriptions-item
          v-show="selectNode?.updateTime"
          label="计算时间"
        >
          {{ selectNode?.updateTime }}
        </el-descriptions-item>
        <el-descriptions-item
          v-show="selectNode?.dataQuality !== null"
          label="质量"
        >
          <el-tag
            v-if="selectNode?.dataQuality === 1"
            size="small"
            type="success"
          >
            good
          </el-tag>
          <el-tag v-else size="small" type="danger">
            good
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item
          v-show="selectNode?.dataValue != null"
          label="值"
        >
          {{ selectNode?.dataValue }}
        </el-descriptions-item>
      </el-descriptions>
    </el-popover>
  </FullscreenModal>
</template>

<style lang="scss" scoped>
.ppp-description {
  :deep(.el-descriptions__label) {
    white-space: nowrap;
  }
  :deep(.el-descriptions__content) {
    word-break: break-all;
  }
}
</style>
